package drds.data_propagate.parse.table_meta_data;

import drds.data_propagate.binlog.event.TableMapEvent;

import java.util.ArrayList;
import java.util.List;

/**
 * 描述数据meta对象,mysql binlog中对应的{@linkplain TableMapEvent}包含的信息不全
 *
 * <pre>
 * 1. 主键信息
 * 2. column name
 * 3. unsigned字段
 * </pre>
 */
public class TableMetaData {

    private String schemaName;
    private String tableName;
    private List<ColumnMetaData> columnMetaDataList = new ArrayList<ColumnMetaData>();
    private String ddl;                                          // 表结构的DDL语句

    public TableMetaData() {

    }

    public TableMetaData(String schemaName, String tableName, List<ColumnMetaData> columnMetaDataList) {
        this.schemaName = schemaName;
        this.tableName = tableName;
        this.columnMetaDataList = columnMetaDataList;
    }

    public String getFullName() {
        return schemaName + "." + tableName;
    }

    public String getSchemaName() {
        return schemaName;
    }

    public void setSchemaName(String schemaName) {
        this.schemaName = schemaName;
    }

    public String getTableName() {
        return tableName;
    }

    public void setTableName(String tableName) {
        this.tableName = tableName;
    }

    public List<ColumnMetaData> getColumnMetaDataList() {
        return columnMetaDataList;
    }

    public void setColumnMetaDataList(List<ColumnMetaData> fileds) {
        this.columnMetaDataList = fileds;
    }

    public ColumnMetaData getColumnMetaData(String columnName) {
        for (ColumnMetaData columnMetaData : columnMetaDataList) {
            if (columnMetaData.getColumnName().equalsIgnoreCase(columnName)) {
                return columnMetaData;
            }
        }

        throw new RuntimeException("unknow column : " + columnName);
    }

    public List<ColumnMetaData> getPrimaryKeyColumnMetaDataList() {
        List<ColumnMetaData> columnMetaDataList = new ArrayList<ColumnMetaData>();
        for (ColumnMetaData columnMetaData : this.columnMetaDataList) {
            if (columnMetaData.isKey()) {
                columnMetaDataList.add(columnMetaData);
            }
        }

        return columnMetaDataList;
    }

    public String getDdl() {
        return ddl;
    }

    public void setDdl(String ddl) {
        this.ddl = ddl;
    }

    public void addFieldMeta(ColumnMetaData columnMetaData) {
        this.columnMetaDataList.add(columnMetaData);
    }

    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append("TableMetaData [schemaName=" + schemaName + ", tableName=" + tableName + ", fileds=");
        for (ColumnMetaData columnMetaData : columnMetaDataList) {
            sb.append("\n\t").append(columnMetaData.toString());
        }
        sb.append("\n]");
        return sb.toString();
    }

}
